package com.auto.learning.base;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.os.IBinder;
import android.os.Looper;
import android.os.Message;
import android.support.v4.app.FragmentActivity;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import com.auto.learning.Application;
import com.auto.learning.R;
import com.auto.learning.activity.LoginActivity;
import com.auto.learning.base.UIHandler.IHandler;
import com.auto.learning.event.listener.DialogListener;
import com.auto.learning.service.MyUserInfo;
import com.auto.learning.view.CommonAlertDialog;
import com.auto.learning.view.MyProgressDialog;

public abstract class BaseActivity extends FragmentActivity {
	
	protected Application application;
	
	protected LinearLayout activity_base_title,activity_base_back,netErrHint,activity_base_content;
	protected ScrollView activity_base_scrollview;
	protected Button retryBtn;
	protected TextView activity_base_titlename;
	
	protected InputMethodManager imm;
	protected MyProgressDialog progressDialog;
	
	protected UIHandler handler = new UIHandler(Looper.getMainLooper());

	@Override
	protected void onCreate(Bundle bundle) {
		super.onCreate(bundle);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE | WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
		super.setContentView(R.layout.activity_base);
		initBaseUI();
		initContentView(bundle);
		initHandler();
	}
	
	private void initBaseUI() {
		application = (Application) getApplication();
		activity_base_back = (LinearLayout) findViewById(R.id.activity_base_back);
		activity_base_content = (LinearLayout) findViewById(R.id.activity_base_content);
		activity_base_scrollview = (ScrollView) findViewById(R.id.activity_base_scrollview);
		activity_base_titlename = (TextView) findViewById(R.id.activity_base_titlename);
		netErrHint = (LinearLayout) findViewById(R.id.ac_base_neterrhint);
		retryBtn = (Button) findViewById(R.id.ac_base_retry);
		imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
		progressDialog = MyProgressDialog.createLoadingDialog(this);
		activity_base_scrollview.setOnTouchListener(new OnTouchListener() {
			@Override
			public boolean onTouch(View v, MotionEvent event) {
				IBinder ib = null;
				try {
					ib = getCurrentFocus().getWindowToken();
				} catch (Exception e) {
					return false;
				}
				if (ib != null) {
					return imm.hideSoftInputFromWindow(ib, 0);
				} else {
					return false;
				}
			}
		});
		activity_base_back.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				BaseActivity.this.finish();
			}
		});
	}
	
	@Override
	public boolean onTouchEvent(MotionEvent event) {
		if (event.getAction() == MotionEvent.ACTION_DOWN) {
			if (this.getCurrentFocus() != null) {
				if (this.getCurrentFocus().getWindowToken() != null) {
					imm.hideSoftInputFromWindow(this.getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
				}
			}
		}
		return super.onTouchEvent(event);
	}
	
	@Override
	protected void onPause() {
		if (progressDialog != null && progressDialog.isShowing()) {
			progressDialog.cancel();
		}
		super.onPause();
	}
	
	@Override
	public void setContentView(int layoutResID) {
		setViewInLine(layoutResID, true);  //默认加载能滑动的
	}

	/**
	 * 当内容为listview或者webview这类可滑动的view时在linearlayout里装载防止与scrollview滑动冲突
	 * @param layoutResID  
	 */
	public void setViewInLine(int layoutResID, boolean canScrollBySelf) {
		if (canScrollBySelf) {
			activity_base_scrollview.setVisibility(View.GONE);
			LayoutInflater inflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
			inflater.inflate(layoutResID, activity_base_content);
		} else {
			activity_base_content.setVisibility(View.GONE);
			LayoutInflater inflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
			inflater.inflate(layoutResID, activity_base_scrollview);
		}
	}
	
	/**
	 * 设置返回键是否可见
	 * @param flag
	 */
	public void setBackBtn(boolean flag) {
		if (flag) {
			activity_base_back.setVisibility(View.VISIBLE);
		} else {
			activity_base_back.setVisibility(View.GONE);
		}
	}
	
	/**
	 * 设置标题名称
	 */
	@Override
	public void setTitle(int resid) {
		activity_base_titlename.setText(resid);
	}

	/**
	 * 设置标题名称
	 */
	public void setTitle(String title) {
		activity_base_titlename.setText(title);
	}
	
	protected abstract void initContentView(Bundle savedInstanceState);  //初始化UI控件
	
    protected abstract void handleMessage(Message msg);   //让子类处理消息
	
    /**
     * 初始化Handle
     */
	private void initHandler(){
		handler.setHandler(new IHandler() {
			
			@Override
			public void handleMessage(Message msg) {
				handleMessage(msg);
			}
		});
	}
	
	/**
	 * 显示提示信息
	 * @param tipMsg  提示内容
	 */
	public void showToastTips(String tipMsg){
		LayoutInflater inflater = LayoutInflater.from(this);
		View layout = inflater.inflate(R.layout.toast_custom_layout, null);
		TextView title = (TextView) layout.findViewById(R.id.toast_custom_tv);
		title.setText(tipMsg);
		Toast t = new Toast(this);
		t.setGravity(Gravity.BOTTOM, 0, 80);
		t.setView(layout);
		t.setDuration(1000);
		t.show();
	}
	
	/***
	 * 显示Dialog
	 * @param btnArray   eg:  String[] btnArray = {"举报","取消"};
	 * @param msg   消息内容  
	 * @param listener   点击按钮回调
	 * @param showTitle  是否显示Dialog Title
	 */
	public void showDialog(String[] btnArray, String msg, DialogListener listener, boolean showTitle){
		CommonAlertDialog alertDialog = new CommonAlertDialog(this);
		alertDialog.setTextMessage(msg);
		alertDialog.setShowTitle(showTitle);
		alertDialog.setBtns(listener, btnArray);
		alertDialog.show();
	}
	
	/***
	 * 显示Dialog(含 Title)
	 * @param btnArray   eg:  String[] btnArray = {"确定","取消"};
	 * @param msg   消息内容  
	 * @param listener  点击按钮回调
	 */
	public void showDialog(String[] btnArray, String msg, DialogListener listener){
		showDialog(btnArray, msg, listener, true);
	}
	
	
	/**
	 * 当图片较大时，加载可能会出现OOM，使用此方法可以稍微避免，但也不是最佳办法。后期待继续优化此方法
	 * @param context
	 * @param resId   
	 * @return
	 */
	public Bitmap readBitMap(Context context, int resId) {
		BitmapFactory.Options opt = new BitmapFactory.Options();
		opt.inPreferredConfig = Bitmap.Config.RGB_565;
		opt.inPurgeable = true;
		opt.inInputShareable = true;
		// 获取资源图片
		InputStream is = context.getResources().openRawResource(resId);
		return BitmapFactory.decodeStream(is, null, opt);
	}
	
	/**
	 * 获取本地图片资源
	 * @param mPath
	 * @return
	 */
	public Bitmap readBitMap(String mPath){
		if (TextUtils.isEmpty(mPath)) {
			return null;
		}
		BitmapFactory.Options opt = new BitmapFactory.Options();
		opt.inPreferredConfig = Bitmap.Config.RGB_565;
		opt.inPurgeable = true;
		opt.inInputShareable = true;
		File file =  new File(mPath);
		InputStream inputStream = null;
		try {
			inputStream = new FileInputStream(file);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return BitmapFactory.decodeStream(inputStream, null, opt);
	}
	
	/**
	 * 检查用户是否登录
	 */
	public boolean checkUserLogin(){
		return checkUserLogin("");
	}
	
	/**
	 * 检查用户是否需要登录
	 * @param msg
	 * @return
	 */
	public boolean checkUserLogin(String msg) {
		boolean flag = true;
		if (TextUtils.isEmpty(MyUserInfo.getInstance().getUserInfoBean().getSessionId())) {
			flag = false;
			String[] btnArray = {getResources().getString(R.string.text_goto_login), getResources().getString(R.string.app_cancel)};
			if (TextUtils.isEmpty(msg)) msg = getResources().getString(R.string.text_no_login);
			showDialog(btnArray, msg, new DialogListener() {
				@Override
				public void otherButtonClick(Dialog dialog) {
					dialog.dismiss();
				}
				
				@Override
				public void okButtonClick(Dialog dialog) {
					dialog.dismiss();
					Intent intent = new Intent(BaseActivity.this, LoginActivity.class);
					startActivityForResult(intent, 100);
				}
				
				@Override
				public void cancelButtonClick(Dialog dialog) {
					dialog.dismiss();
				}
			});
		}
		return flag;
	}
	
	/**
	 * 
	 * @param cotext
	 * @return 0 AS 断网       1 AS WIFI       2 AS 234G网络
	 */
	public int getNetworkState(Context context) {
		ConnectivityManager mConnMgr = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo mWifi = mConnMgr.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
		NetworkInfo mMobile = mConnMgr.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
		int flag = 0;
		if ((mWifi != null) && ((mWifi.isAvailable()) || (mMobile.isAvailable()))) {
			if (mWifi.isConnected()) {
				flag = 1;
			}
			if (mMobile.isConnected()) {
				flag = 2;
			}
		}
		return flag;
	}
	
	/**
	 * dip转为 px
	 */
	public int dip2px(Context context, int dipValue) {
		final float scale = context.getResources().getDisplayMetrics().density;
		return (int) (dipValue * scale + 0.5f);
	}

	/**
	 * px 转为 dip
	 */
	public int px2dip(Context context, float pxValue) {
		final float scale = context.getResources().getDisplayMetrics().density;
		return (int) (pxValue / scale + 0.5f);
	}
	
	/**
	 * 获取网络数据
	 */
	public void getData(){
		
	}
}
